<?php

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\validate\TokenGet;
use app\api\service\UserToken;
use app\api\service\Token as TokenService;
use app\api\exception\ParameterException;
use app\api\validate\AppTokenGet;
use app\api\service\AppToken;

class Token extends BaseController
{

    /**
     * 用户获取令牌（登陆）
     * @url /token
     * @POST code
     * @note 虽然查询应该使用get，但为了稍微增强安全性，所以使用POST
     */
    public function getToken($code = '')
    {
//        检测输入
        (new TokenGet())->goCheck();
//       初始化
        $wx_token = new UserToken($code);
//       获取token
        $token = $wx_token->getAndSave();
        return [
            'token' => $token
        ];
    }

    public function verifyToken($token = '')
    {
        if (!$token)
        {
            $option = [
                'token不允许为空'
            ];
            throw new ParameterException($option);
        }
        $valid = TokenService::verifyToken($token);
        return [
            'isValid' => $valid
        ];
    }

    /**
     * 第三方应用获取令牌
     * @url /app_token?
     * @POST ac=:ac se=:secret
     */
    public function getAppToken($ac = '', $se = '')
    {
//        跨域
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: GET');
        (new AppTokenGet())->goCheck();
        $app = new AppToken();
        $token = $app->getAndSave($ac, $se);
        return [
            'token' => $token
        ];
    }

}
